package com.qf.controller;

import com.qf.convert.MyConvert;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.MD5Utils;
import com.qf.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

/**
 * 前台用户注册后台入口
 */
@WebServlet("/userRegister")
public class UserRegisterServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //校验验证码
        String code = request.getParameter("code");//用户前台输入的验证码
        //获取session
        HttpSession session = request.getSession();
        //从session域中获取服务器端的存储的验证码
        String CHECKCODE_SERVER = (String) session.getAttribute("CHECKCODE_SERVER");
        //一次性验证码
        session.removeAttribute("CHECKCODE_SERVER");
        if(code==null || !code.equalsIgnoreCase(CHECKCODE_SERVER)){
            //错误提示
            request.setAttribute("msg","验证码错误!");
            request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response);
            return ;
        }


        //1)接收参数
        Map<String, String[]> map = request.getParameterMap();
        //2)创建User对象,封装数据 --工具类 commons-beantuls
        User user = new User() ;

        //处理日期
        ConvertUtils.register(new MyConvert(), Date.class);

        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //封装其他数据
        user.setUid(UUIDUtils.getId());
        //密码加密
        user.setPassword(MD5Utils.md5(user.getPassword())) ;
        //激活码
        user.setCode(UUIDUtils.getCode());

        //调用业务接口
        UserService userService = new UserServiceImpl() ;
        userService.registerUser(user) ;

        //用户注册成功
        //给request域中添加一个绑定参数数据
        request.setAttribute("msg","恭喜您,用户注册成功");
        request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response);



    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
    }
}
